import { h, render, shallowReactive } from 'vue'
import messageInstance from './index.vue'
import { ICreateMessageProps, IMessageInstance } from './type'

let seed = 1

const instances = shallowReactive<IMessageInstance[]>([])

const createMessage = (props: ICreateMessageProps) => {
  const id = `message_${seed++}`
  const container = document.createElement('div')

  const destory = () => {
    const index = instances.findIndex((item) => item.id === id)
    if (index === -1) return
    instances.splice(index, 1)
    render(null, container)
  }

  const newProps = {
    ...props,
    id,
    destory
  }

  const vNode = h(messageInstance, newProps)
  render(vNode, container)
  document.body.appendChild(container.firstElementChild as HTMLElement)
  const vm = vNode.component! as any
  const instance = {
    id,
    props: newProps,
    vNode,
    vm
  }
  instances.push(instance)
  return instance
}

// 获得最后一个元素向上的偏移值(top值)
export const getLastMessageTopDistance = (id: string) => {
  const idx = instances.findIndex((item) => item.id === id)
  if (idx <= 0) return 0
  const distance = instances[idx - 1].vm.exposed?.nextOffsetTop.value
  return distance
}

export default createMessage
